package com.lishem.carl._01array;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode.cn/problems/spiral-matrix/description/
 * <p>
 * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 * <p>
 * 示例 1：
 * <p>
 * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 * <p>
 * 输出：[1,2,3,6,9,8,7,4,5]
 * <p>
 * 示例 2：
 * <p>
 * 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
 * <p>
 * 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
 */
public class _10LetCode54_螺旋矩阵 {

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        int left = 0;
        int right = matrix[0].length - 1;
        int top = 0;
        int bottom = matrix.length - 1;
        int i;
        while (left <= right && top <= bottom) {
            if (left == right || top == bottom) {
                if (left == right) {
                    while (top <= bottom) {
                        list.add(matrix[top++][left]);
                    }
                } else {
                    while (left <= right) {
                        list.add(matrix[top][left++]);
                    }
                }
            } else {
                i = left;
                while (i < right) {
                    list.add(matrix[top][i++]);
                }
                i = top;
                while (i < bottom) {
                    list.add(matrix[i++][right]);
                }
                i = right;
                while (i > left) {
                    list.add(matrix[bottom][i--]);
                }
                i = bottom;
                while (i > top) {
                    list.add(matrix[i--][left]);
                }
            }
            left++;
            top++;
            right--;
            bottom--;
        }
        return list;
    }


    public static void main(String[] args) {
        _10LetCode54_螺旋矩阵 sol = new _10LetCode54_螺旋矩阵();
        int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        System.out.println(sol.spiralOrder(matrix1));
        int[][] matrix2 = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        System.out.println(sol.spiralOrder(matrix2));
    }
}
